package org.csu.springjpetstore.persistence.util;

import java.sql.*;

public class DBUtil {

    private final static String DRIVER_CLASS = "com.mysql.jdbc.Driver";
    private final static String CONNECTION_STRING = "jdbc:mysql://112.74.55.242:3306/plant_store?useUnicode=true&characterEncoding=utf8&useSSL=false";
    private final static String USERNAME = "root";
    private final static String PASSWORD = "123456";

    public static Connection getConnection() throws Exception {
        Class.forName(DRIVER_CLASS);
        Connection connection = DriverManager.getConnection(CONNECTION_STRING, USERNAME, PASSWORD);
        return connection;
    }

    public static void closeConnection(Connection connection) throws Exception {
        if (connection != null) {
            connection.close();
        }
    }

    public static void closeStatement(Statement statement) throws Exception {
        if (statement != null) {
            statement.close();
        }
    }

    public static void closePreparedStatement(PreparedStatement preparedStatement) throws Exception {
        if (preparedStatement != null) {
            preparedStatement.close();
        }
    }

    public static void closeResultSet(ResultSet resultSet) throws Exception {
        if (resultSet != null) {
            resultSet.close();
        }
    }

//    /**
//     * 根据结果集给单个数据库对象赋值
//     *
//     * @param resultSet 结果集
//     * @param dbObject  数据库对象
//     * @throws SQLException
//     */
//    public static void setDBObjectByResultSet(ResultSet resultSet, DBObject dbObject) throws SQLException {
//        if (dbObject instanceof User) {
//            ((User) dbObject).setId(resultSet.getInt("id"));
//            ((User) dbObject).setUsername(resultSet.getString("username"));
//            ((User) dbObject).setPassword(resultSet.getString("password"));
//            ((User) dbObject).setGender(resultSet.getString("gender"));
//            ((User) dbObject).setAge(resultSet.getInt("age"));
//            ((User) dbObject).setEmail(resultSet.getString("email"));
//        } else if (dbObject instanceof Product) {
//
//        }
//    }

    public static void main(String[] args) {
        try {
            Connection connection = DBUtil.getConnection();
            System.out.println("数据库连接测试: " + connection.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
